package com.gimi.cloud.jimi.client.service.moreInfo.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gimi.cloud.jimi.client.service.moreInfo.CreditcardEmailService;
import com.gimi.cloud.jimi.common.enums.ResponseCodeEnum;
import com.gimi.cloud.jimi.common.exception.MsgException;
import com.gimi.cloud.jimi.common.mq.service.MqCommonSenderService;
import com.gimi.cloud.jimi.common.utils.DateUtil;
import com.gimi.cloud.jimi.common.utils.Page;
import com.gimi.cloud.jimi.common.utils.StringUtil;
import com.gimi.cloud.jimi.common.utils.reqhead.Response;
import com.gimi.cloud.jimi.commonService.InterfacePlatform.InterfacePlatformRequestService;
import com.gimi.cloud.jimi.common.mq.enume.QueueEnum;
import com.gimi.cloud.jimi.dao.dao.User.UserDao;
import com.gimi.cloud.jimi.dao.dao.moreInfo.FengchaoEmailDao;
import com.gimi.cloud.jimi.dao.dao.moreInfo.FengchaoPositionDao;
import com.gimi.cloud.jimi.dao.dao.moreInfo.MoreInfoDao;
import com.gimi.cloud.jimi.dao.dao.sys.SysConfigDao;
import com.gimi.cloud.jimi.dao.redis.IRedisService;
import com.gimi.cloud.jimi.dto.app.moreInfo.FengchaoEmailDTO;
import com.gimi.cloud.jimi.dto.app.moreInfo.FengchaoPositionDTO;
import com.gimi.cloud.jimi.entity.app.moreInfo.FengchaoEmailEntity;
import com.gimi.cloud.jimi.entity.app.moreInfo.MoreInfoEntity;
import com.gimi.cloud.jimi.entity.user.User;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @auther loongs
 * @date 2018/1/12  17:32
 */
@Service
public class CreditcardEmailServiceImpl implements CreditcardEmailService {

    private static final Logger log = LoggerFactory.getLogger(CreditcardEmailServiceImpl.class);

    private FengchaoEmailDao fengchaoEmailDao;
    private FengchaoPositionDao fengchaoPositionDao;
    private SysConfigDao sysConfigDao;
    private InterfacePlatformRequestService requestService;
    private UserDao userDao;
    private IRedisService iRedisService;
    private MqCommonSenderService commonSenderService;
    private MoreInfoDao moreInfoDao;

    //最大容错次数暂时定为3次
    private final Integer MAXTIMES = 3;

    private final String INTERFACE_PLATFORM_UNIVERSAL_CREDITCARDEMAIL = "interface_platform_universal_creditCardEmail";

    @Autowired
    public CreditcardEmailServiceImpl(FengchaoEmailDao fengchaoEmailDao, FengchaoPositionDao fengchaoPositionDao, SysConfigDao sysConfigDao,
                                      InterfacePlatformRequestService requestService, UserDao userDao, IRedisService iRedisService,
                                      MqCommonSenderService commonSenderService, MoreInfoDao moreInfoDao) {
        this.fengchaoEmailDao = fengchaoEmailDao;
        this.fengchaoPositionDao = fengchaoPositionDao;
        this.sysConfigDao = sysConfigDao;
        this.requestService = requestService;
        this.userDao = userDao;
        this.iRedisService = iRedisService;
        this.commonSenderService = commonSenderService;
        this.moreInfoDao = moreInfoDao;
    }

    @Override
    public Response getFengchaoEmailList(FengchaoEmailDTO fengchaoEmailDTO) {
        Response response = new Response();
        Map<String, Object> data = new HashMap<>();
        List<FengchaoEmailEntity> fengchaoEmailEntityList = fengchaoEmailDao.selectAll();
        data.put("emailList", fengchaoEmailEntityList);
        response.setRes_data(data);
        response.setResponseCode(ResponseCodeEnum.SUCCESSED);
        return response;
    }

    @Override
    public Response getFengchaoPositionList(FengchaoPositionDTO fengchaoPositionDTO) {
        Response response = new Response();
        Map<String, Object> data = new HashMap<>();
        PageHelper.startPage(fengchaoPositionDTO.getCurrentPage(), fengchaoPositionDTO.getPageSize());
        List<FengchaoPositionDTO> result = fengchaoPositionDao.queryPageList(fengchaoPositionDTO);
        Page<FengchaoPositionDTO> page = new Page(new PageInfo<>(result));
        data.put("positionList", page);
        response.setRes_data(data);
        response.setResponseCode(ResponseCodeEnum.SUCCESSED);
        return response;
    }

    @Override
    public Response getFengchaoEmailLogin(FengchaoEmailDTO fengchaoEmailDTO) {
        Response response = new Response();
        User user = userDao.getUserByUserId(fengchaoEmailDTO.getUserId());
        if (user == null) {
            throw new MsgException(ResponseCodeEnum.ERR_USER_INVALID);
        }
        log.info("蜂巢信用卡邮箱登录开始");
        String creditCardEmail = sysConfigDao.getConfigByKey(INTERFACE_PLATFORM_UNIVERSAL_CREDITCARDEMAIL);
        JSONObject feJson = JSON.parseObject(creditCardEmail);
        JSONObject loginJson = feJson.getJSONObject("fengchao_creditCard_email_login");
        JSONObject body = loginJson.getJSONObject("body");
        body.put("userName", fengchaoEmailDTO.getUserName());
        body.put("passWord", fengchaoEmailDTO.getPassWord());
        body.put("fetchLimit", fengchaoEmailDTO.getFetchLimit());
        body.put("position", fengchaoEmailDTO.getPosition());

        loginJson.put("body", body);
        log.info("蜂巢信用卡邮箱登录，拼装参数：" + loginJson.toJSONString());

        log.info("提交基本参数尝试登陆");

        try {
            String resStr = requestService.sendApiPost(loginJson.toJSONString());
            JSONObject resJson = JSON.parseObject(resStr);
            JSONObject resbody = resJson.getJSONObject("body");
            String appemailkey = resbody.getString("appemailkey");
            if (resbody == null) {
                response.setResponseCode(ResponseCodeEnum.FENGCHAO_EMAIL_LOGIN_EXCEPTION);
                return response;
            }
            //登录失败，0是登录成功
            if (StringUtil.isBlank(resbody.get("code")) || !"0".equals(resbody.get("code"))) {
                throw new MsgException(ResponseCodeEnum.FENGCHAO_EMAIL_LOGIN_EXCEPTION, resbody.getString("msg"));
            }
            Integer operUserId = fengchaoEmailDTO.getUserId();
            return getFengchaoEmailStatus(appemailkey, operUserId);

        } catch (Exception e) {
            log.info("基本参数登录异常" + e.getClass());
            e.printStackTrace();
            response.setResponseCode(ResponseCodeEnum.SERVICE_ERROR);
            return response;
        }
    }

    @Override
    public Response getFengchaoEmailStatus(String appemailkey, Integer operUserId) {
        Response response = new Response();
        User user = userDao.getUserByUserId(operUserId);
        if (user == null) {
            throw new MsgException(ResponseCodeEnum.ERR_USER_INVALID);
        }
        log.info("蜂巢邮箱状态查询开始");
        String creditCardEmail = sysConfigDao.getConfigByKey(INTERFACE_PLATFORM_UNIVERSAL_CREDITCARDEMAIL);
        JSONObject feJson = JSON.parseObject(creditCardEmail);
        JSONObject statusJson = feJson.getJSONObject("fengchao_creditCard_email_status");
        JSONObject body = statusJson.getJSONObject("body");
        body.put("appemailkey", appemailkey);

        statusJson.put("body", body);
        log.info("蜂巢邮箱状态查询，拼装参数：" + statusJson.toJSONString());

        String resStr = null;
        JSONObject resJson=null;
        JSONObject bodyJson=null;
        String messageType=null;
        try {
            //如果是登录中的话就让接口重复调用
            do {
                 //半秒调一次，此方法有待优化
                 Thread.sleep(500);

                 resStr = requestService.sendApiPost(statusJson.toJSONString());
                 resJson = JSON.parseObject(resStr);
                 bodyJson = resJson.getJSONObject("body");
                 messageType = bodyJson.getString("messageType");
            }while ("1".equals(messageType));

            if (bodyJson == null || StringUtil.isBlank(messageType)) {
                response.setResponseCode(ResponseCodeEnum.FENGCHAO_EMAIL_STATUS_EXCEPTION);
                return response;
            }
            response.setRes_data(bodyJson);
            switch (messageType) {
                case "300":
                    log.info("正在收取邮件,放入队列当中");
                    initMoreInfoAndSentToMq(operUserId, appemailkey);
                    break;
                case "1000":
                    log.info("执行完成,放入队列当中");
                    initMoreInfoAndSentToMq(operUserId, appemailkey);
                    break;
                case "2":
                    log.info("登录成功,放入队列当中");
                    initMoreInfoAndSentToMq(operUserId, appemailkey);
                    break;
                default:
                    response.setResponseCode(ResponseCodeEnum.LOGIN_EXCEPTION, bodyJson.getString("message"));
                    return response;
            }
            response.setResponseCode(ResponseCodeEnum.SUCCESSED);
            return response;
        } catch (Exception e) {
            log.info("蜂巢邮箱状态查询异常" + e.getClass());
            e.printStackTrace();
            response.setResponseCode(ResponseCodeEnum.SERVICE_ERROR);
            return response;
        }
    }

    /**
     * 初始化一些数据，且丰乳队列中
     * @param operUserId
     * @param appemailkey
     * @throws Exception
     */
    private void initMoreInfoAndSentToMq(Integer operUserId, String appemailkey) throws Exception {
        User user = userDao.getUserByUserId(operUserId);
        if (user == null) {
            throw new MsgException(ResponseCodeEnum.ERR_USER_INVALID);
        }
        //查询该用户之前是否有获取过信用卡邮箱，需要获取状态为获取中
        MoreInfoEntity moreInfoEntity = moreInfoDao.getMoreInfoByUserIdAndType(operUserId,5);

        //半段是不是新增，true是新增，false已存在
        boolean flag = false;
        //返回值为2的时候，是代表时间已经过期
        if (moreInfoEntity != null && (DateUtil.compare(moreInfoEntity.getReportEffectionEnd(), DateUtil.getNow()) == 2 ||
                (DateUtil.compare(moreInfoEntity.getReportEffectionEnd(), DateUtil.getNow()) == 0 && !"2".equals(moreInfoEntity.getGetdata())))) {
            //如果是有效期内，就做修改，不做新增
            //如果是失败的且过期时间为空，就需要做修改，不做新增
        }else {
            //时间过期了的新增
            moreInfoEntity = new MoreInfoEntity();
            moreInfoEntity.setGetdataTime(new Date());
            moreInfoEntity.setAnalysis("0");

            //user相关
            moreInfoEntity.setAddTime(new Date());
            moreInfoEntity.setAddUname(user.getAddUname());
            moreInfoEntity.setAddUid(user.getUserId());
            moreInfoEntity.setUserId(user.getUserId());

            //5代表信用邮箱账单
            moreInfoEntity.setDataType("5");
            moreInfoEntity.setGetdataMaxTimes(MAXTIMES);

            flag = true;
        }
        //获取中
        moreInfoEntity.setGetdata("1");
        if (flag) {
            moreInfoDao.insertSelective(moreInfoEntity);
        } else {
            moreInfoEntity.setUpdateUid(user.getUserId());
            moreInfoEntity.setUpdateUname(user.getAddUname());
            moreInfoEntity.setUpdateTime(DateUtil.getNow());
            moreInfoDao.updateByPrimaryKey(moreInfoEntity);
        }
        //封装发送到队列里的参数
        FengchaoEmailDTO fengchaoEmailDTO = new FengchaoEmailDTO();
        fengchaoEmailDTO.setUserId(operUserId);
        fengchaoEmailDTO.setAppemailkey(appemailkey);
        commonSenderService.sendMessage2Rabbitmq(QueueEnum.FENGCHAO_XINYONGKAYOUXIANGZHANGDAN_REPORT, fengchaoEmailDTO);
    }

    @Override
    public Response subFengchaoEmailIndependentPassWord(FengchaoEmailDTO fengchaoEmailDTO) {
        Response response = new Response();
        User user = userDao.getUserByUserId(fengchaoEmailDTO.getUserId());
        if (user == null) {
            throw new MsgException(ResponseCodeEnum.ERR_USER_INVALID);
        }
        log.info("蜂巢邮箱独立密码提交接口开始");
        String creditCardEmail = sysConfigDao.getConfigByKey(INTERFACE_PLATFORM_UNIVERSAL_CREDITCARDEMAIL);
        JSONObject feJson = JSON.parseObject(creditCardEmail);
        JSONObject independentpasswordJson = feJson.getJSONObject("fengchao_creditCard_email_independentpassword");
        JSONObject body = independentpasswordJson.getJSONObject("body");
        body.put("appemailkey", fengchaoEmailDTO.getAppemailkey());
        body.put("ivdPassword", fengchaoEmailDTO.getIvdPassword());

        independentpasswordJson.put("body", body);
        log.info("蜂巢邮箱独立密码提交接口，拼装参数：" + independentpasswordJson.toJSONString());

        String resStr = null;
        try {
            resStr = requestService.sendApiPost(independentpasswordJson.toJSONString());
            JSONObject resJson = JSON.parseObject(resStr);
            JSONObject bodyJson = resJson.getJSONObject("body");
            if (bodyJson == null) {
                response.setResponseCode(ResponseCodeEnum.INDEPENDENTPASSWORD_EMAIL_EXCEPTION);
                return response;
            }
//            response.setRes_data(bodyJson);
//            response.setResponseCode(ResponseCodeEnum.SUCCESSED);
//            return response;

            //状态接口去等待才能获取结果
            Thread.sleep(2 * 1000);

            return getFengchaoEmailStatus( fengchaoEmailDTO.getAppemailkey(),  fengchaoEmailDTO.getUserId());
        } catch (Exception e) {
            log.info("蜂巢邮箱独立密码提交接口异常" + e.getClass());
            e.printStackTrace();
            response.setResponseCode(ResponseCodeEnum.SERVICE_ERROR);
            return response;
        }
    }

    @Override
    public Response subFengchaoEmailValidCode(FengchaoEmailDTO fengchaoEmailDTO) {
        Response response = new Response();
        User user = userDao.getUserByUserId(fengchaoEmailDTO.getUserId());
        if (user == null) {
            throw new MsgException(ResponseCodeEnum.ERR_USER_INVALID);
        }
        log.info("蜂巢邮箱登验证码提交接口开始");
        String creditCardEmail = sysConfigDao.getConfigByKey(INTERFACE_PLATFORM_UNIVERSAL_CREDITCARDEMAIL);
        JSONObject feJson = JSON.parseObject(creditCardEmail);
        JSONObject validcodeJson = feJson.getJSONObject("fengchao_creditCard_email_validcode");
        JSONObject body = validcodeJson.getJSONObject("body");
        body.put("appemailkey", fengchaoEmailDTO.getAppemailkey());
        body.put("validCode", fengchaoEmailDTO.getValidCode());

        validcodeJson.put("body", body);
        log.info("蜂巢邮箱登验证码提交接口，拼装参数：" + validcodeJson.toJSONString());

        String resStr = null;
        try {
            resStr = requestService.sendApiPost(validcodeJson.toJSONString());
            JSONObject resJson = JSON.parseObject(resStr);
            JSONObject bodyJson = resJson.getJSONObject("body");
            if (bodyJson == null) {
                response.setResponseCode(ResponseCodeEnum.VALIDCODE_FENGCHAO_EMAIL_EXCEPTION);
                return response;
            }
//            response.setRes_data(bodyJson);
//            response.setResponseCode(ResponseCodeEnum.SUCCESSED);
//            return response;

            //状态接口去等待才能获取结果
            Thread.sleep(2 * 1000);
            return getFengchaoEmailStatus( fengchaoEmailDTO.getAppemailkey(),  fengchaoEmailDTO.getUserId());
        } catch (Exception e) {
            log.info("蜂巢邮箱登验证码提交接口异常" + e.getClass());
            e.printStackTrace();
            response.setResponseCode(ResponseCodeEnum.SERVICE_ERROR);
            return response;
        }
    }
}
